<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use App\Http\Resources\CategoryResource;
use Jiannei\Response\Laravel\Support\Facades\Response;

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $categoriesTree = Category::get()->toTree(); // 获取全部节点的集合，将它转化为树
        //return Response::success(CategoryResource::collection($categoriesTree));
        return Response::success($categoriesTree);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // 创建节点
        // 数据结构示例见 database/seeders/CategorySeeder.php
        $inputData = $request->all();

        if ($inputData['parent_id'] ) {
            // 如示例数据$nestArrDeomC，则创建子节点，一次只能添加一条
            $parent = Category::find($inputData['parent_id'] ); // 已存在的节点，做为新添加节点的父节点
            $result = $parent->children()->create($inputData['node']); //借助父节点的children关系,添加子节点到指定的父节点末端
        }else {
            // 请求数据结构如示例数据$nestArrDeomA或$nestArrDeomB，将数组构建为树，只能有一个root节点 ，但可以有许多个子孙节点。
            $result = Category::create($inputData['node']); // 将数组构建为树
        }

        return Response::success(new CategoryResource($result));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function show(Category $category)
    {
        //
        return Response::success(new CategoryResource($category));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Category $category)
    {
        // put 请求，修改节点名称
        $category->name = $request->name;
        $category->save();

        return Response::success(new CategoryResource($category));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Category  $category
     * @return \Illuminate\Http\Response
     */
    public function destroy(Category $category)
    {
        return Response::success($category->delete()); // 返回 boolean 值
    }
}
